import React, { useState, useEffect } from "react";
import { Button, Upload, message, Image, Flex, } from "antd";
import { DeleteOutlined, EyeOutlined, LinkOutlined } from '@ant-design/icons';
import useUpload from "./useUpload";
import './index.scss';
import { ACCEPT_TYPE, DEFAULTATTACHMENTURL } from '../../../../utils/constant';
import { useTranslation } from 'react-i18next';
import { debounce } from "../../../../utils/commonUtil";
import { apiSysBatchUpload } from '../../../../services/common'
import _ from 'lodash';
import DeleteConfirm from '../../../Components/DeleteConfirm';

const UploadImg = ({
  // 上传或删除更新
  uploadUpdateFn,
  // 是否disabled
  disabled,
  // fileList
  fileListData,
  // 最大上传数量
  maxCount = 20,
  //点击链接图标方法
  linkFn,
  //隐藏上传文字
  isHideText,
  //上传前过滤方法
  beforeFilterFn,

  className,

}) => {
  const { t } = useTranslation();
  const { TYPE, VERIFIED } = ACCEPT_TYPE.JPGTIF;
  const acceptImg = TYPE?.join(',');

  const [visible, setVisible] = useState(false);
  // 已上传的文件列表
  const [fileList, setFileList] = useState(fileListData || []);
  // 每次新上传的文件
  const [appendFileList, setAppendFileList] = useState(fileListData || []);
  useEffect(() => {
    setFileList(fileListData);
  }, [fileListData]);
  const onChangeFile = (newFileList) => {
    uploadUpdateFn(newFileList);
  }

  const onRemove = ({ file, fileList }) => {
    DeleteConfirm({
      t,
      title: t('common.deleteFileMsg'),
      onOk() {
        uploadUpdateFn([], true);
      }
    });
  }



  const imgRender = (file) => {
    return (
      <>
        <div className="uploadImg">
          <Flex className="iconGroup">
            {
              linkFn && <div className="icon" onClick={() => linkFn(file)}><LinkOutlined className="icon" /></div>
            }
            <div className="icon" onClick={() => setVisible(true)}><EyeOutlined className="icon" /></div>
            {
              !disabled && <div className="icon" onClick={() => onRemove(file, fileList, onChangeFile)}><DeleteOutlined className="icon" /></div>
            }

          </Flex>
          <Image
            className="img"
            preview={visible ? {
              visible,
              onVisibleChange: (value) => {
                setVisible(value);
              },
            } : false}
            src={DEFAULTATTACHMENTURL + file?.attachmentUrl}
          />
        </div>
        {file?.attachmentName && <div className='fileName' title={file.attachmentName}>{file.attachmentName}</div>}
      </>
    )
  }


  const MAX_SIZE = 1;
  const beforeUpload = (file, list) => {
    console.log("🚀 ~ beforeUpload ~ list:", list)
    // 判断最后一个文件是否添加进来
    if (file?.uid === list?.[list?.length - 1]?.uid) {
      // 判断上传数量
      if (fileList?.length + list?.length > maxCount) {
        message.error(t('common.uploadTipsSum'));
        return false;
      };
      let filterList = list
      if (beforeFilterFn) {
        filterList = beforeFilterFn(list)
        if (!filterList || filterList.length === 0) {
          return false
        }
      }
      // 文件总大小
      let filesSize = 0;
      // 判断文件格式
      for (let fileItem of filterList) {
        const type = fileItem?.type || fileItem?.name?.split('.')?.pop()?.toLowerCase();
        filesSize += fileItem.size;
        const isValidType = VERIFIED?.includes(type);
        if (!isValidType && VERIFIED?.length !== 0) {
          message.error(t('common.uploadTips', { type: TYPE }));
          return false;
        };
      };
      console.log("filesSize", filesSize)
      // 判断文件总大小 GB
      if (filesSize / 1024 / 1024 / 1024 > MAX_SIZE) {
        message.error(t('common.uploadTipsSize'));
        return false;
      };
      setAppendFileList(filterList);
      return true;
    } else {
      return false;
    }
  };

  const customRequest = debounce(() => {
    const param = new FormData();
    appendFileList.map((file) => {
      param.append('files', file);
    });
    apiSysBatchUpload(param).then((res) => {
      if (res?.data) {
        const resFiles = res?.data?.data?.items?.map((item, index) => {
          return {
            ...item,
            uid: index,
            name: item?.attachmentName,
            status: 'done',
            url: item?.attachmentUrl,
          }
        });
        uploadUpdateFn([...fileList, ...resFiles]?.map(item => {
          return {
            ..._.omit(item, ['uid', 'name', 'status', 'url'])
          }
        }));
      };
    });
  }, 300);

  return (
    <>
      {
        fileList.length > 0 ? (
          <div className="uploadImgWrap">{imgRender(fileList[0])}</div>
        ) : (
          <div className={`${className ? className : ''} uploadImgWrap`}>
            <Upload
              className="uploadImg"
              listType="picture-card"
              defaultFileList={fileList}
              fileList={fileList}
              accept={acceptImg}
              multiple={true}
              beforeUpload={beforeUpload}
              customRequest={customRequest}
              maxCount={maxCount}
              disabled={disabled}
            >
              {isHideText ? <div /> : fileList.length < 1 && `+${t('common.upload')}`}
            </Upload>
            <div className='fileName' >&nbsp;</div>
          </div>
        )
      }


    </>

  )
}

export default UploadImg;